package com.briup.es.service.impl;

import com.briup.es.config.auth.UserDetails;
import com.briup.es.config.response.ResultCode;
import com.briup.es.domain.bean.Shopcar;
import com.briup.es.domain.vo.ShopCarVO;
import com.briup.es.mapper.BookMapper;
import com.briup.es.mapper.ShopcarMapper;
import com.briup.es.service.ShopCarService;
import com.briup.es.utils.AssertUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ShopCarServiceImpl implements ShopCarService {

    @Resource
    private BookMapper bookMapper;
    @Resource
    private ShopcarMapper shopcarMapper;

    @Override
    public void addShopCar(Integer bookId) {
        // 根据id查询图书，确定图书是否还存在
        int num = bookMapper.queryById(bookId);
        AssertUtil.isTrue(num == 1, ResultCode.BOOK_IS_NOT_EXISTS);
        // 获取当前登录用户的id
        Integer userId = UserDetails.userId();
        // 根据指定的用户id和BookId查询数据库中是否存在已有的购物车项
        Shopcar shopcar = shopcarMapper.queryByUserIdAndBookId(userId, bookId);
        if (shopcar == null) {
            shopcar = new Shopcar(null, userId, bookId, num);
            // 如果不存在，那么直接添加
            // 将购物车实体数据通过mapper层写入到数据库中
            shopcarMapper.addShopCar(shopcar);
        } else {
            // 如果购物车中存在该图书的购物车项，那么直接修改购物车项的数量
            // 在已有的数量基础上加1
            shopcarMapper.updateNumById(shopcar.getId(), shopcar.getNum() + 1);
        }
    }

    @Override
    public List<ShopCarVO> queryAll() {
        // 获取当前登录用户的id
        Integer userId = UserDetails.userId();
        return shopcarMapper.queryAllByUserId(userId);
    }

    @Override
    public void updateNumById(Integer id, Integer num) {
        // 直接通过购物车项，修改该项的数量
        shopcarMapper.updateNumById(id, num);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        // 直接使用sql删除即可
        shopcarMapper.deleteBatch(ids);
    }
}
